package com.cat.dataStructure;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/range-sum-query-mutable/
 * @create 2025/9/28 14:43
 * @since JDK17
 */

public class NumArray {
    int[] tree;
    int[] nums;
    int n;
    public NumArray(int[] nums) {
        n = nums.length;
        tree = new int[n + 1];
        this.nums = new int[n];
        for (int i = 0; i < nums.length; i++) {
            update(i, nums[i]);
        }
    }

    public void update(int index, int val) {
        int t = val - nums[index];
        nums[index] = val;
        for (int i = index + 1; i <= n; i += i & -i) {  // 向上更新
            tree[i] += t;
        }
    }
    int sum(int i) {
        int ans = 0;
        for (; i > 0; i -= i & -i) {
            ans += tree[i];
        }
        return ans;
    }
    public int sumRange(int left, int right) {
        return sum(right + 1) - sum(left);
    }
}

